package cn.ee.dfs.wx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static cn.ee.dfs.wx.WebConst.SecretKey.KEY_DEFAULT;


/**
 * description:
 * author: TWJ
 * date: 2019/1/22 0022 上午 11:19
 */
public class TokenUtil {

    private static Logger lg = LoggerFactory.getLogger(TokenUtil.class);

    /**
     * 生成注册token串
     */
    public static String createToken(String timeStamp, String userCode, String openId) {
        String token = "";
        ArrayList<String> sortStr = new ArrayList<String>();
        sortStr.add(KEY_DEFAULT);
        sortStr.add(timeStamp);
        if (!StringUtils.isEmpty(userCode)) {
            sortStr.add(userCode);
        }
        sortStr.add(openId);
        Collections.sort(sortStr);
        for (int i = 0; i < sortStr.size(); i++) {
            token += sortStr.get(i);
        }
        token = MD5Util.MD5(token);

        return token;
    }


    public static String createCustomFreshmanToken(List<String> list) {
        String token = "";
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            token += list.get(i);
        }
        token = MD5Util.MD5(token);
        return token;
    }


    /**
     *
     */
    public static String generateToken(String openId) {

        String[] str = {WebConst.SecretKey.KEY_USR_INFO, WebConst.SecretKey.KEY_BASE, StringUtils.isEmpty(openId) ? "1" : openId};
//        lg.info("----  before sort ->" + Arrays.toString(str));
        Arrays.sort(str);
//        lg.info("----  after sort ->" + Arrays.toString(str));
        String token = MD5Util.MD5(str[0] + str[1] + str[2]);
//        lg.info("---- after md5 ->" + token);
        return token;
    }

    public static String generateToken(String... keys) {
        List<String> list = new ArrayList<>();
        for (String key :
                keys)
            list.add(StringUtils.isEmpty(key) ? "1" : key);
        list.add(WebConst.SecretKey.KEY_USR_INFO);
        list.add(WebConst.SecretKey.KEY_BASE);

        Object[] str = list.toArray();

//        lg.info("---- much before sort ->" + Arrays.toString(str));
        Arrays.sort(str);


//        lg.info("---- much after sort ->" + Arrays.toString(str));
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length; i++) {
            sb.append(str[i]);
        }
        String token = MD5Util.MD5(sb.toString());
        lg.info("---- much after md5 ->" + token);
        return token;
    }


}
